package home;

import java.io.IOException;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import reports.DetailReport;
import server.Initialize;
import server.db.StmtHelper;
import server.objects.Photo;

import ajaxmethods.AjaxMethod;

public class ScrollableListings implements AjaxMethod {

	
	
	@Override
	public void perform(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text/json");

		try {
			new JSONObject().put("fade",true).put("htmlSelector","#homeWorkspace #scrollWrapper").put("htmlValue",out(request.getParameter("listingType")).toString()).write(response.getWriter());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static StringBuffer out(String listingrequestType)
	{
		StringBuffer sb = new StringBuffer();
		Map<String, List<String>> map = new HashMap<String,List<String>>();
		StmtHelper prep = StmtHelper.db("select zillowID,price,useCode,finishedSQFT,bathrooms,bedrooms, (select concat(street,' ',city,', ',state,' ',zip))  as ADDRESS,"+
				" ifnull((select image_url from photos where photos.zillowID=alllist.zillowID and photos.photo_num=1),'"+Photo.getNoPhotoURL()+"') IMGURL"+
				" from alllist ");
		if(listingrequestType==null || listingrequestType.equals("newlistings"))
		{
			try {
				map =  prep.addSql("where type='Not for sale' || type='For sale by owner' group by useCode,finishedSQFT,bathrooms,bedrooms,street,city,state,zip,zillowID limit 20").collectStrings.unsafeGet();
			
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if(listingrequestType.equals("pricedrops"))
		{
			try {
				//TODO:change where clause to return listings with price changes
				//Requires having the ACTRIS DATA
				map =  prep.addSql("where type='For sale by agent' group by useCode,finishedSQFT,bathrooms,bedrooms,street,city,state,zip,zillowID limit 20").collectStrings.unsafeGet();
			
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if(listingrequestType.equals("foreclosures"))
		{
			try {
				map =  prep.addSql("where type='Make me move' group by useCode,finishedSQFT,bathrooms,bedrooms,street,city,state,zip,zillowID limit 20").collectStrings.unsafeGet();
			
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if(listingrequestType.equals("mylistings"))
		{
			try {
				map =  prep.addSql("where type='Make me move' group by useCode,finishedSQFT,bathrooms,bedrooms,street,city,state,zip,zillowID limit 20").collectStrings.unsafeGet();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
			sb.append("<div class=\"scrollable\">");
			sb.append("<div class=\"items\">");
			for(int i = 0; i < map.get("useCode").size(); i ++)
			{
				String zillow = map.get("zillowID").get(i);
				String typ = map.get("useCode").get(i);
				String address = map.get("ADDRESS").get(i);
				String beds = map.get("bedrooms").get(i);
				String sqft = map.get("finishedSQFT").get(i);
				String primaryphoto = map.get("IMGURL").get(i);
				String bathrooms = map.get("bathrooms").get(i);
				String price = NumberFormat.getCurrencyInstance().format(Integer.parseInt(map.get("price").get(i)));
				sb.append("<div class=\"mediumReport\">");
				sb.append("<div class=\"content\" style=\"position: relative;margin-left:6px;width: 886px;height: 380px;\">" +
						"<div id=\"photo\"><div class=\"medphotosize\">" +
						"<a class=\"fancyphotoLink\" id=\""+zillow+"\" title=\""+address+"\"><img style=\"height: 260px;margin-top: 40px;\" src=\""+primaryphoto+"\"></a></div></div>");
				
				sb.append("<div id=\"propertyBrief\">");
				sb.append("");
				sb.append("<h3 class=\"propaddress\">"+address+"</h3>");
				sb.append("<div class=\"price\"><span class=\"label\">Price:</span>"+price+"</div>");
				sb.append("<div class=\"beds\"><span class=\"label\">Bedrooms:</span>"+beds+"</div>");
				sb.append("<div class=\"baths\"><span class=\"label\">Bathrooms:</span>"+bathrooms+"</div>");
				sb.append("<div class=\"proptype\"><span class=\"label\">Property Type:</span>"+typ+"</div>");
				sb.append("<div class=\"sqft\"><span class=\"label\">Square Feet:</span>"+sqft+"</div>");
				sb.append("<div class=\"linkWrapper\"><div id=\"detailview\"><a  id=\""+zillow+"\" title=\""+address+"\" class=\"detailLink moredetails\">More Details</a></div></div>");
				sb.append("</div>");
				sb.append("</div></div>");	
			}	
			sb.append("</div>");
			sb.append("<script>");
			sb.append("$('.fancyphotoLink').click(function(){var link = $(this); if(link.find('img').attr('src').indexOf('nophotoavail')==-1)$.post('"+Initialize.appURL()+"/ajaxCall.jsp?do=reports.Photos',{zillowID:link.attr('id')},function(data, textStatus, XMLHttpRequest) {"+
			"	if(data){$.fancybox(data,{title:link.attr('title'),type:'image', transitionIn:'elastic',transitionOut:'elastic',easingIn:'easeOutBack',easingOut:'easeInBack',width:500});}});}); ");
			sb.append(DetailReport.javaScriptOut());
			sb.append("</script>");
		return sb;
	}

}
